<?php
include($_SERVER['DOCUMENT_ROOT']."/inc/Function_index.php");
upower();
$cartlist = cartlist();
$id = isset($_GET['id'])?intval($_GET['id']):0;
$address = cart_address($id);
if($cartlist){
    $total = $cartlist[0]['total'];
    $cplx = $cartlist[0]['cplx'];
    $kuaidi = $cartlist[0]['kuaidi'];
}else{
    $total = 0;
    $cplx = 0;
    $kuaidi = 0;
}

// 查询可置换订单列表
$exchange_orders = array();
if($cartlist && $cplx == 2){
    // 获取商品类型
    $gid = $cartlist[0]['gid'];
    $db_temp = new db($conf);
    $ginfo = $db_temp->field(array("type"))->where("Id=$gid")->select("sc_goods");
    if($ginfo){
        $gtype = $ginfo[0]['type'];
        // 查询该用户所有可置换的订单（同类型、已完成、未置换、未退单）
        $info = userinfo();
        $exchange_orders = $db_temp->field(['o.*'])->where("o.uid=".$info['Id']." and o.gtype=$gtype and o.zh=0 and o.jhstate>0 and o.state=4 and o.td=0")->order('o.Id asc')->select("sc_orders as o");
        
        // 解析每个订单的商品信息
        if($exchange_orders){
            for($i=0; $i<count($exchange_orders); $i++){
                $exchange_orders[$i]['glist'] = json_decode($exchange_orders[$i]['goods'], true);
            }
        }
    }
}

$tpl->assign("kuaidi",$kuaidi);
$tpl->assign("cplx",$cplx);
$tpl->assign("total",$total);
$info = userinfo();
$tpl->assign("info",$info);
$tpl->assign("clist",$cartlist);
$tpl->assign("addlist",$address);
$tpl->assign("exchange_orders",$exchange_orders);  // 传递可置换订单列表
$tpl->assign('results',$results);
$tpl->show("cart");
?>